<template>
  <div class="shelf-footer" v-show="isEditMode">
    <div
      class="shelf-footer-tab-wrapper"
      v-for="item in tabs"
      :key="item.index"
      @click="onTabClick(item)"
    >
      <!-- 书架底部Tab栏 -->
      <div class="shelf-footer-tab" :class="{ 'is-selected': isSelected }">
        <!-- [私密阅读]图标 -->
        <div
          class="icon-private tab-icon"
          v-if="item.index === 1 && !isPrivate"
        ></div>
        <div
          class="icon-private-see tab-icon"
          v-if="item.index === 1 && isPrivate"
        ></div>

        <!-- [开启离线]图标 -->
        <div
          class="icon-download tab-icon"
          v-if="item.index === 2 && !isDownLoad"
        ></div>
        <div
          class="icon-download-remove tab-icon"
          v-if="item.index === 2 && isDownLoad"
        ></div>

        <!-- [移动到...]图标 -->
        <div class="icon-move tab-icon" v-if="item.index === 3"></div>

        <!-- [移除书架]图标 -->
        <div class="icon-shelf tab-icon" v-if="item.index === 4"></div>

        <!-- 图标对应的文本 -->
        <div class="tab-text" :class="{ 'remove-text': item.index === 4 }">
          {{ label(item) }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { removeLocalStorage, saveBookShelf } from '@/utils/localStorage';
import { storeShelfMixin } from '@/utils/mixin';
import { download } from '@/api/store';
import { removeLocalForage } from '@/utils/localForage';

export default {
  mixins: [storeShelfMixin],
  computed: {
    // 是否被选中
    isSelected() {
      // 判断选中电子书的数组是否存在 && 长度是否大于0
      return this.shelfSelected && this.shelfSelected.length > 0;
    },
    // 动态计算Tab栏文本
    tabs() {
      return [
        {
          label: this.$t('shelf.private'),
          label2: this.$t('shelf.noPrivate'),
          index: 1,
        },
        {
          label: this.$t('shelf.download'),
          label2: this.$t('shelf.delete'),
          index: 2,
        },
        {
          label: this.$t('shelf.move'),
          index: 3,
        },
        {
          label: this.$t('shelf.remove'),
          index: 4,
        },
      ];
    },

    // 书是否是私密阅读状态
    isPrivate() {
      // 没有书本选中直接false
      if (!this.isSelected) {
        return false;
      }
      // 有书本选中,且每本书都是私密阅读状态返回True,否则返回False
      else {
        return this.shelfSelected.every((item) => item.private);
      }
    },

    // 书是否已经处于离线下载的缓存状态
    isDownLoad() {
      // 没有书本选中直接false
      if (!this.isSelected) {
        return false;
      }
      // 有书本选中,且每本书都是缓存状态返回True,否则返回False
      else {
        return this.shelfSelected.every((item) => item.cache);
      }
    },
  },
  data() {
    return {
      popupMenu: null, // 弹窗菜单
    };
  },
  methods: {
    // 下载选中的电子书
    async downloadSelectedBook() {
      // 遍历书架里被选中的电子书
      for (let i = 0; i < this.shelfSelected.length; i++) {
        await this.downloadBook(this.shelfSelected[i]).then((book) => {
          book.cache = true;
        });
      }
    },
    // 下载电子书
    downloadBook(book) {
      let text = '';
      const toast = this.toast({
        text,
      });
      toast.continueShow();
      return new Promise((resolve, reject) => {
        download(
          book,
          (book) => {
            toast.remove();
            resolve(book);
          },
          reject,
          (progressEvent) => {
            // 下载进度
            const progress =
              Math.floor((progressEvent.loaded / progressEvent.total) * 100) +
              '%';
            // 下载进度文本
            text = this.$t('shelf.progressDownload').replace(
              '$1',
              `${book.fileName}.epub(${progress})`
            );
            toast.updateText(text);
          }
        );
      });
    },
    onComplete() {
      // 隐藏tab栏
      this.hidePopup();
      // 取消编辑状态
      this.setIsEditMode(false);
      // 将修改的数据保存到书架中
      saveBookShelf(this.shelfList);
    },
    hidePopup() {
      this.popupMenu.hide();
    },
    setPrivate() {
      let isPrivate;
      if (this.isPrivate) {
        isPrivate = false;
      } else {
        isPrivate = true;
      }
      this.shelfSelected.forEach((book) => {
        book.private = isPrivate;
      });
      this.downloadSelectedBook();
      this.onComplete();
      if (isPrivate) {
        this.simpleToast(this.$t('shelf.setPrivateSuccess'));
      } else {
        this.simpleToast(this.$t('shelf.closePrivateSuccess'));
      }
    },
    // 私密阅读弹框
    showPrivate() {
      this.popupMenu = this.popup({
        title: this.private
          ? this.$t('shelf.closePrivateTitle')
          : this.$t('shelf.setPrivateTitle'),
        btn: [
          {
            text: this.isPrivate
              ? this.$t('shelf.close')
              : this.$t('shelf.open'),
            click: () => {
              this.setPrivate();
            },
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup();
            },
          },
        ],
      }).show();
    },

    removeSelectedBook() {
      Promise.all(this.shelfSelected.map((book) => this.removeBook(book))).then(
        (books) => {
          books.map((book) => {
            book.cache = false;
          });
          saveBookShelf(this.shelfList);
          this.simpleToast(this.$t('shelf.removeDownloadSuccess'));
        }
      );
    },

    removeBook(book) {
      return new Promise((resolve, reject) => {
        removeLocalStorage(`${book.categoryText}/${book.fileName}-info`);
        removeLocalForage(`${book.fileName}`);
        resolve(book);
      });
    },
    // 离线缓存功能
    async setDownload() {
      this.onComplete();
      // 已经下载则显示移除文本
      if (this.isDownLoad) {
        this.removeSelectedBook();
      }
      // 未下载则进行下载,并显示下载文本
      else {
        await this.downloadSelectedBook();
        saveBookShelf(this.shelfList);
        this.simpleToast(this.$t('shelf.setDownloadSuccess'));
      }
    },
    // 离线下载弹窗
    showDownLoad() {
      this.popupMenu = this.popup({
        title: this.isDownLoad
          ? this.$t('shelf.removeDownloadTitle')
          : this.$t('shelf.setDownloadTitle'),
        btn: [
          {
            text: this.isDownLoad
              ? this.$t('shelf.delete')
              : this.$t('shelf.open'),
            click: () => {
              this.setDownload();
            },
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup();
            },
          },
        ],
      }).show();
    },

    // 移除所选的图书
    removeSelected() {
      this.shelfSelected.forEach((selected) => {
        this.setShelfList(this.shelfList.filter((book) => book !== selected));
      });
      this.setShelfSelected([]);
      this.onComplete();
    },

    // 移除图书弹窗
    showRemove() {
      let title;
      // 如果所选电子书的长度为1,标题为电子书书名
      if (this.shelfSelected.length === 1) {
        title = this.$t('shelf.removeBookTitle').replace(
          '$1',
          `《${this.shelfSelected[0].title}》`
        );
      } else {
        title = this.$t('shelf.removeBookTitle').replace(
          '$1',
          this.$t('shelf.selectedBooks')
        );
      }

      this.popupMenu = this.popup({
        title: title,
        btn: [
          {
            text: this.$t('shelf.removeBook'),
            type: 'danger',
            click: () => {
              this.removeSelected();
            },
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup();
            },
          },
        ],
      }).show();
    },

    // 点击Tab栏动态渲染内容
    onTabClick(item) {
      if (!this.isSelected) {
        return;
      }
      switch (item.index) {
        case 1:
          this.showPrivate();
          break;
        case 2:
          this.showDownLoad();
          break;
        case 3:
          this.dialog().show();
          break;
        case 4:
          this.showRemove();
          break;
        default:
          break;
      }
    },
    label(item) {
      switch (item.index) {
        case 1:
          return this.isPrivate ? item.label2 : item.label;
        case 2:
          return this.isDownLoad ? item.label2 : item.label;
        default:
          return item.label;
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import '../../assets/styles/global';
.shelf-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 120;
  display: flex;
  width: 100%;
  height: px2rem(48);
  background: #fff;
  box-shadow: 0 px2rem(-2) px2rem(4) 0 rgba(0, 0, 0, 0.1);

  .shelf-footer-tab-wrapper {
    flex: 1;
    width: 25%;
    height: 100%;

    .shelf-footer-tab {
      width: 100%;
      height: 100%;
      @include columnCenter;
      opacity: 50%;

      &.is-selected {
        opacity: 1;
      }

      .tab-icon {
        font-size: px2rem(20);
        color: #666;
      }

      .tab-text {
        margin-top: px2rem(5);
        font-size: px2rem(12);
        color: #666;

        &.remove-text {
          color: $color-pink;
        }
      }

      .is-selected {
        opacity: 1;
      }

      .icon-shelf {
        color: $color-pink;
      }
    }
  }
}
</style>
